package com.sunny.ynhz.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.sunny.ynhz.api.HttpManager;
import com.sunny.ynhz.api.NetUrl;
import com.sunny.ynhz.bean.ImageBean;
import com.sunny.ynhz.ui.base.BaseWebActivity;
import com.sunny.ynhz.utils.SPUtil;
import com.sunny.ynhz.utils.ShowUtils;
import com.sunny.ynhz.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;

/**
 * Created by hhh on 2017/12/15.
 */

public class WaitForToCheckActivity extends BaseWebActivity {
    File mLocalfile;
    private StringBuffer localPath;
    private StringBuffer servicePath;
    ArrayList<String> stringArrayListExtra = new ArrayList<>();
    HashMap<String, String> mpathHash = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("待复核");
    }

    @Override
    public void loadUrl(String url) {
        String url1 = NetUrl.baseUrl + "pages/patrol_problem/dfu_list.jsp?" + "userId=" + SPUtil.get("userId", "null");
        super.loadUrl(url1);
    }

    public void setOpenImageManager(String path) {
        stringArrayListExtra.clear();
        if (!TextUtils.isEmpty(path)) {
            String splitStr = path.split("\\|\\|")[0];
            String[] split = splitStr.split(",");
            for (int i = 0; i < split.length; i++) {
                String local = split[i];
                stringArrayListExtra.add(local);
            }
        }
        PhotoPickerIntent intent = new PhotoPickerIntent(this);
        intent.setSelectModel(SelectModel.MULTI);
        intent.setShowCarema(true); // 是否显示拍照， 默认false
        intent.setMaxTotal(9); // 最多选择照片数量，默认为9
        intent.setSelectedPaths(stringArrayListExtra); // 已选中的照片地址， 用于回显选中状态
        this.startActivityForResult(intent, 202);
    }

    @Override
    public void showUploadActivity(String path) {
        setOpenImageManager(path);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 202 && data != null && resultCode == RESULT_OK) {//图片类
            stringArrayListExtra.clear();
            stringArrayListExtra.addAll(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
            List<File> mlist = new ArrayList<>();
            for (int i = 0; i < stringArrayListExtra.size(); i++) {
                mlist.add(new File(stringArrayListExtra.get(i)));
            }
            uploadImgs(mlist);
        }
    }

    private void uploadImgs(final List<File> mlist) {
        localPath = new StringBuffer();
        servicePath = new StringBuffer();
        Observable.from(mlist).filter(file -> file.length() > 0).filter(file -> {
            String absolutePath = file.getAbsolutePath();
            if (mpathHash.get(absolutePath) != null) {
                localPath.append(absolutePath + ",");
                servicePath.append(mpathHash.get(absolutePath) + ",");
                return false;
            }
            return true;
        }).flatMap(file -> {
            mLocalfile = file;
            return Luban.get(WaitForToCheckActivity.this).load(file).putGear(Luban.THIRD_GEAR).asObservable().last();
        }).flatMap(file -> {
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            String imageName = file.getName();
            if (!(imageName.endsWith(".png") || imageName.endsWith(".jpg") || imageName.endsWith(".jpeg") || imageName.endsWith("bmp"))) {
                imageName = imageName + ".png";
            }
            MultipartBody.Part body = MultipartBody.Part.createFormData("file", imageName, requestFile);
            return HttpManager.getInstance().uploadHandlerImg("www", body);
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<ImageBean>() {
            @Override
            public void onCompleted() {
                StringBuffer relLocalPaths = localPath.replace(localPath.length() - 1, localPath.length(), "");
                StringBuffer relServicePaths = servicePath.replace(servicePath.length() - 1, servicePath.length(), "");
                String service = relLocalPaths.toString() + "||" + relServicePaths;
                String url = "javascript:getImagePathFromAndroid('" + service + "')";
                mWebView.loadUrl(url);
                ShowUtils.closePopwindow();
            }

            @Override
            public void onError(Throwable e) {
                ShowUtils.closePopwindow();
                ToastUtils.SingleToastUtil(WaitForToCheckActivity.this, "上传失败");
            }

            @Override
            public void onNext(ImageBean imageBean) {
                String mNewPath = imageBean.getNewPath();
                String mLocalPath = mLocalfile.getAbsolutePath();
                localPath.append(mLocalPath + ",");
                servicePath.append(mNewPath + ",");
                mpathHash.put(mLocalPath, mNewPath);
            }

            @Override
            public void onStart() {
                super.onStart();
                ShowUtils.inItPopwin(WaitForToCheckActivity.this, "请等待");
            }
        });
    }
}
